import React, {useState} from "react";
import {Button, Grid} from "@material-ui/core";
import {AddRounded} from "@material-ui/icons";

import withSpinner from "../../hoc/withSpinner";
import {renderViewAction} from "../../shared/utilities/uiTemplate.util";
import {EnhancedTable, Toolbar} from "../../shared/components";
import {getProducts} from "../../shared/services/data.service";

const ViewAllProduct = ({onAdd, onRowClick, ...props}) => {
    const [products, setProducts] = useState([]);

    const getProductList = () => (
        new Promise((resolve, reject) => {
            getProducts().then(res => {
                setProducts(res.data);
                resolve(res.data);
            }).catch(error => reject(error));
        })
    );

    return (
        <Grid container spacing={4}>
            <Toolbar
                title="Products"
                actions={<React.Fragment>
                    <Button variant="contained" color="primary" startIcon={<AddRounded/>} onClick={onAdd}>Add Product</Button>
                </React.Fragment>}
            />

            <Grid item xs={12}>
                <EnhancedTable
                    title={"Product List"}
                    schema={[
                        {id: 'id', label: '', hidden: true},
                        {id: 'name', label: 'Name', sort: true},
                        {id: 'std_tonnage', label: 'Tonnage', sort: true}
                    ]}
                    async={{loading: true, loadingData: getProductList}}
                    pagination={products.length > 5}
                    onRowClick={onRowClick}
                />
            </Grid>
        </Grid>
    );
};

export default withSpinner(ViewAllProduct);
